package com.example.forwardmessages

import android.content.Context
import android.content.SharedPreferences

/**
 * 应用配置类，负责管理所有应用配置
 */
class AppConfig(private val context: Context) {
    companion object {
        private const val PREFS_NAME = "SMSSettings"
        
        // 默认配置值 TODO
        private const val DEFAULT_SMTP_SERVER = "smtp.qq.com"
        private const val DEFAULT_SMTP_PORT = 587
        // TODO 替换为自己的邮箱 发件箱
        private const val DEFAULT_EMAIL_USER = "a@qq.com"
        private const val DEFAULT_EMAIL_PASSWORD = "123456"
        // TODO 替换为自己的邮箱 收件箱 
        private const val DEFAULT_RECIPIENT_EMAIL = "a@qq.com"
        private const val DEFAULT_RECIPIENT_EMAIL_SIM1 = "b@qq.com"
        private const val DEFAULT_RECIPIENT_EMAIL_SIM2 = "c@qq.com"
    }
    
    private val sharedPreferences: SharedPreferences by lazy {
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    }
    
    // SMTP服务器地址
    val smtpServer: String
        get() = sharedPreferences.getString("smtpServer", DEFAULT_SMTP_SERVER) ?: DEFAULT_SMTP_SERVER
    
    // SMTP服务器端口
    val smtpPort: Int
        get() = sharedPreferences.getString("smtpPort", DEFAULT_SMTP_PORT.toString())?.toIntOrNull() ?: DEFAULT_SMTP_PORT
    
    // 邮箱用户名
    val emailUser: String
        get() = sharedPreferences.getString("emailUser", DEFAULT_EMAIL_USER) ?: DEFAULT_EMAIL_USER
    
    // 邮箱密码
    val emailPassword: String
        get() = sharedPreferences.getString("emailPassword", DEFAULT_EMAIL_PASSWORD) ?: DEFAULT_EMAIL_PASSWORD
    
    // 收件人邮箱
    val recipientEmail: String
        get() = sharedPreferences.getString("recipientEmail", DEFAULT_RECIPIENT_EMAIL) ?: DEFAULT_RECIPIENT_EMAIL
    
    // 获取SIM1收件人邮箱
    val recipientEmailSim1: String
        get() = sharedPreferences.getString("recipientEmailSim1", DEFAULT_RECIPIENT_EMAIL_SIM1) ?: DEFAULT_RECIPIENT_EMAIL_SIM1
    
    // 获取SIM2收件人邮箱
    val recipientEmailSim2: String
        get() = sharedPreferences.getString("recipientEmailSim2", DEFAULT_RECIPIENT_EMAIL_SIM2) ?: DEFAULT_RECIPIENT_EMAIL_SIM2
    
    // 检查邮箱配置是否完整
    fun isEmailConfigComplete(): Boolean {
        return emailUser.isNotEmpty() && emailPassword.isNotEmpty() && recipientEmail.isNotEmpty()
    }
    
    // 根据SIM卡信息获取对应的收件人邮箱
    fun getRecipientEmailBySimInfo(simInfo: String?): String {
        if (simInfo.isNullOrEmpty()) {
            return recipientEmail
        }
        
        // 检测SIM卡信息中是否包含SIM1或SIM2，或者subscriptionId为1或2
        return when {
            simInfo.contains("SIM1") || simInfo.contains("sim1") || simInfo.contains("subscriptionId: 1") -> recipientEmailSim1
            simInfo.contains("SIM2") || simInfo.contains("sim2") || simInfo.contains("subscriptionId: 2") -> recipientEmailSim2
            else -> recipientEmail
        }
    }
}